package com.hc.mybatis.generator.plugins;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.internal.util.StringUtility;
import org.mybatis.generator.internal.util.messages.Messages;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 修改model类后缀
 * @author: hc
 * @version: v1.0
 * @create at: 2020/7/15 19:48
 * @reviewer:
 * @review at:
 *
 * Revision history:
 * date             author      version     content
 * ------------------------------------------------------------
 * 2020/7/15           hc          v1.0        XXXX
 */
public class RenameModelClassPlugin extends PluginAdapter {

    private String searchString;
    private String replaceString;
    private Pattern pattern;

    public RenameModelClassPlugin() {
    }

    @Override
    public boolean validate(List<String> warnings) {
        this.searchString = this.properties.getProperty("searchString");
        this.replaceString = this.properties.getProperty("replaceString");
        boolean valid = StringUtility.stringHasValue(this.searchString) && StringUtility.stringHasValue(this.replaceString);
        if (valid) {
            this.pattern = Pattern.compile(this.searchString);
        } else {
            if (!StringUtility.stringHasValue(this.searchString)) {
                warnings.add(Messages.getString("ValidationError.18", "RenameModelClassPlugin", "searchString"));
            }

            if (!StringUtility.stringHasValue(this.replaceString)) {
                warnings.add(Messages.getString("ValidationError.18", "RenameModelClassPlugin", "replaceString"));
            }
        }

        return valid;
    }

    @Override
    public void initialized(IntrospectedTable introspectedTable) {
        String oldType = introspectedTable.getBaseRecordType();
        Matcher matcher = this.pattern.matcher(oldType);
        oldType = matcher.replaceAll(this.replaceString);
        introspectedTable.setBaseRecordType(oldType);
    }

}